package org.apache.cordova.openmap;
import android.content.Intent;
import android.net.Uri;
import android.widget.Toast;

import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;

/**
 * Created by SHAOHUI on 2017/3/10.
 */
public class OpenMap extends CordovaPlugin{
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if("openMap".equals(action)){
            openMap(args.getString(0), args.getString(1));
        }
        callbackContext.success();
        return true;
    }
    private void openMap(String url,String pageName){
        if(pageName.equals("高德地图")){
            Intent i1 = new Intent();
            // 驾车导航lat=36.547901&lon=104.258354
            Intent intent = new Intent("android.intent.action.VIEW", Uri.parse("androidamap://navi?sourceApplication=appname&poiname=fangheng&"+url+"&dev=1&style=2"));
            intent.setPackage("com.autonavi.minimap");
            if(isInstallByRead("com.autonavi.minimap")){
                cordova.getActivity().startActivity(intent);
            }else{
                android.widget.Toast.makeText(cordova.getActivity(), "没有安装高德地图，建议选择其他地图", Toast.LENGTH_SHORT).show();
            }
        }else if(pageName.equals("百度地图")){
           Intent i1 = new Intent();
            i1.setData(Uri.parse("baidumap://map/navi?location="+url));
			if(isInstallByRead("com.baidu.BaiduMap")){
				cordova.getActivity().startActivity(i1);
            }else{
                android.widget.Toast.makeText(cordova.getActivity(), "没有安装百度地图，建议选择其他地图", Toast.LENGTH_SHORT).show();
            }
        }else if(pageName.equals("腾讯地图")){
            //Intent i1 = new Intent();
            //i1.setData(Uri.parse("baidumap://map/newsassistant"));
            //cordova.getActivity().startActivity(i1);
			android.widget.Toast.makeText(cordova.getActivity(), "暂时不支持腾讯地图，建议选择其他地图", Toast.LENGTH_SHORT).show();
        }
    }
    /**
     * 根据包名检测某个APP是否安装
     * <h3>Version</h3> 1.0
     *
     * @param packageName 包名
     * @return true 安装 false 没有安装
     */
    public static boolean isInstallByRead(String packageName) {
        return new File("/data/data/" + packageName).exists();
    }


}
